package com.ask.task;

import com.ask.entity.Dish;
import com.ask.service.RecommendService;
import com.ask.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.ask.constant.NumberConstant.SEVEN_DAYS;
import static com.ask.constant.RedisConstant.RECOMMEND_DAILY_KEY;

@Component
public class DailyRecommendTask {

    @Autowired
    private RecommendService recommendService;

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Scheduled(cron = "0 0 1 * * ?") // 每天凌晨1点执行
    public void generateDailyRecommendations() {
        // 1. 获取近7天活跃用户
        List<Long> activeUsers = userService.getActiveUsersLast7Days();

        // 2. 并行处理生成推荐
        activeUsers.parallelStream().forEach(userId -> {
            // 3. 生成某个用户的每日推荐列表
            List<Dish> recommendations = recommendService.generateDailyRecommendations(userId);

            // 4. 存储到Redis, key: userId + date
            String key = RECOMMEND_DAILY_KEY  + userId + ":" + LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE);

            recommendations.forEach(dish -> {
                redisTemplate.opsForZSet().add(key, dish.getId().toString(), dish.getSales());
            });

            // 设置过期时间
            redisTemplate.expire(key, SEVEN_DAYS, TimeUnit.DAYS);
        });
    }
}
